<?php
declare (strict_types=1);

namespace app\common\model;

use think\facade\Cache;
use think\facade\Event;

class Product extends Base
{
    protected $name = 'product';

    public function cate1()
    {
        return $this->hasOne(ProductCate::class, 'id', 'cate_1')->field('id,title');
    }

    public function cate2()
    {
        return $this->hasOne(ProductCate::class, 'id', 'cate_2')->field('id,title');
    }

    public static function submit($param, $user): array
    {
        try {
            $all = [];
            $info = parent::where(['id' => $param['id'], 'is_del' => 0, 'status' => 1])->find();
            if (empty($info)) {
                return ['code' => -1, 'msg' => '商品不存在或已下架'];
            }
            if (!$info->price || $info->price <= 0) {
                return ['code' => -1, 'msg' => '商品价格错误'];
            }
            if ($info->stock < $param['num']) {
                return ['code' => -1, 'msg' => '商品库存不足'];
            }
            $all[] = [
                'pid' => $info->id,
                'num' => $param['num'],
                'cate_1' => $info->cate_1,
            ];

            Cache::set('tsOrder_' . $user->id, json_encode($all));

            return ['code' => 4, 'msg' => 'success', 'url' => url('order/index')->build()];

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


}
